import {config} from "../config.js"

const tips = {
  1:"出现了一个错误",
  1005:"appkey无效",
  3000:"期刊不存在",
}

class HTTP{
  request({url,data={},method='GET'}){
    return new Promise((resolve,reject)=>{
      this._request(url,resolve,reject,data,method)
    })
  }
  _request(url,resolve,reject,data={},method='GET'){
    wx.request({
      url: config.api_base_url+url,
      method:method,
      data:data,
      header:{
        "content-type":"application/json",
        "appkey":config.appkey
      },
      success:(res)=>{
        let code = res.statusCode.toString()
        if(code.startsWith('2')){ // 返回的状态码以2开头
          resolve(res.data)
        }else{
          let err_code = res.data.error_code
          console.log(err_code);
          this._show_err(err_code)
        }
      },
      fail:(err)=>{
        this._show_err(1)
      }
    })
  }
  _show_err(err_code){
    if(!err_code){
      err_code = 1
    }
    const tip = tips[err_code]
    wx.showToast({ // 显示错误信息
      title: tip?tip:tips[1], // 错误信息标题
      icon:"none",  // 图标
      duration:2000  // 显示时间延迟
    })
  }
}
export {HTTP} 